package com.caigou.component;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @FileName: HttpComponent
 * @Author: 小飞
 * @Date: 2021/9/28 0028
 * @Description:
 */
@Slf4j
@Component
public class HttpComponent {

    @Value("${sso.requestUrl}")
    private String ssoRequestUrl;

    public boolean getTokenStatus(String userId, Integer platform, Integer source){
        try {
            // 网络请求类
            CloseableHttpClient httpClient = SSLClientComponent.createHttpClient();
            HttpPost httpPost;
            HttpResponse httpResponse;
            HttpEntity entity;
            // 公共请求参数
            URIBuilder builder = new URIBuilder(ssoRequestUrl);
            httpPost = new HttpPost(builder.build());// post请求方式
            //准备json数据发送参数
            JSONObject param = new JSONObject();
            param.put("userId", userId);
            param.put("platform", platform);
            param.put("source", source);
            //处理中文乱码问题
            StringEntity stringEntity = new StringEntity(param.toString(),"utf-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            //发送请求
            httpResponse = httpClient.execute(httpPost);
            entity = httpResponse.getEntity();
            JSONObject responseJSON = JSONObject.parseObject(EntityUtils.toString(entity));
            if (responseJSON.getString("status").equals("200")){
                // 接口请求成功
                // 接口请求成功--获取data中的数据
                String data = responseJSON.getString("data");
                if (null != data && !data.equals("")){
                    if (data.equals("1")){
                        log.info("登录状态获取成功");
                        return true;
                    } else {
                        log.info("登录状态获取失败");
                        return false;
                    }
                } else {
                    log.error("未获取到数据，data为空 param={}",param);
                    return false;
                }
            } else {
                log.error("接口请求不通，接口状态不为200 param={}",param);
                return false;
            }
        } catch (Exception e){
            log.error(e.getMessage(),e);
            return false;
        }
    }
}
